<template>
  <DynamicDetailDialog
    v-model="visible"
    :title="title"
    :groups="detailGroups"
    :loading="loading"
    width="1200px"
  >
    <!-- 推理进度自定义 slot -->
    <template #inference_progress="{ value }">
      <el-progress
        :percentage="
          typeof value === 'number'
            ? value
            : typeof value === 'string'
            ? parseInt(value) || 0
            : 0
        "
        :status="
          (typeof value === 'number'
            ? value
            : typeof value === 'string'
            ? parseInt(value) || 0
            : 0) === 100
            ? 'success'
            : undefined
        "
      />
    </template>
  </DynamicDetailDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import DynamicDetailDialog, {
  type DetailGroup,
} from "@/components/DynamicDetailDialog";
import { getGithubTaskDetail } from "../../../servers";
import { ElMessage } from "element-plus";

interface Props {
  modelValue: boolean;
  taskId?: number | null;
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  taskId: null,
  title: "任务详情",
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "close"): void;
  (e: "export", taskId: number): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
    if (!value) {
      emit("close");
    }
  },
});

const loading = ref(false);
const taskDetail = ref<any>(null);

// 监听弹窗打开，获取任务详情
watch(
  () => [visible.value, props.taskId],
  ([newVisible, newTaskId]) => {
    if (newVisible && newTaskId && typeof newTaskId === "number") {
      fetchTaskDetail(newTaskId);
    } else {
      taskDetail.value = null;
    }
  },
  { immediate: true }
);

// 获取任务详情
const fetchTaskDetail = async (taskId: number) => {
  loading.value = true;
  try {
    const result = await getGithubTaskDetail(taskId);
    if (result.code === 2000) {
      taskDetail.value = result.data || {};
    } else {
      ElMessage.error(result.message || "获取任务详情失败");
      taskDetail.value = null;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取任务详情失败");
    taskDetail.value = null;
  } finally {
    loading.value = false;
  }
};

// 格式化场景类型
const formatScenarioTypes = (scenarioTypes: string) => {
  if (!scenarioTypes) return "-";
  try {
    const scenarios = JSON.parse(scenarioTypes);
    if (Array.isArray(scenarios) && scenarios.length > 0) {
      return scenarios.join(", ");
    }
  } catch (e) {
    // 解析失败，返回原值
  }
  return scenarioTypes || "-";
};

// 格式化执行频率
const formatCronExpression = (cron: string) => {
  if (!cron) return "-";
  if (cron === "0 */6 * * *") return "每6小时";
  if (cron === "0 0 * * *") return "每天";
  if (cron === "*/15 * * * *") return "每15分钟";
  return cron;
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<
    string,
    "success" | "warning" | "info" | "danger" | ""
  > = {
    pending: "warning",
    running: "info",
    completed: "success",
    failed: "danger",
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待执行",
    running: "执行中",
    completed: "已完成",
    failed: "失败",
  };
  return statusMap[status] || status;
};

// 获取执行状态标签类型
const getRunStatusTagType = (status: string) => {
  const statusMap: Record<
    string,
    "success" | "warning" | "info" | "danger" | ""
  > = {
    success: "success",
    failed: "danger",
    running: "info",
  };
  return statusMap[status] || "info";
};

// 获取执行状态文本
const getRunStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    success: "成功",
    failed: "失败",
    running: "运行中",
  };
  return statusMap[status] || status || "-";
};

// 计算推理进度百分比
const calculateInferenceProgress = (task: any) => {
  const total =
    (task.pending_inference || task.pending_count || 0) +
    (task.inferred || task.inferred_count || 0) +
    (task.confirmed || task.confirmed_count || 0) +
    (task.rejected || task.rejected_count || 0);

  if (total === 0) return 0;

  const completed =
    (task.inferred || task.inferred_count || 0) +
    (task.confirmed || task.confirmed_count || 0) +
    (task.rejected || task.rejected_count || 0);

  return Math.round((completed / total) * 100);
};

// 详情分组数据
const detailGroups = computed<DetailGroup[]>(() => {
  if (!taskDetail.value) return [];

  const task = taskDetail.value;
  const inferenceProgress =
    task.inference_progress !== undefined
      ? task.inference_progress
      : calculateInferenceProgress(task);

  return [
    // 统计卡片
    ...(task.statistics
      ? [
          {
            title: "统计信息",
            type: "statistics" as const,
            statistics: {
              items: [
                {
                  label: "总扫描数",
                  value: task.statistics.total_scanned ?? 0,
                },
                {
                  label: "告警数量",
                  value: task.statistics.alert_count ?? 0,
                },
                {
                  label: "已确认",
                  value: task.statistics.confirmed_count ?? 0,
                },
                {
                  label: "误报数量",
                  value: task.statistics.false_positive_count ?? 0,
                },
                {
                  label: "高危",
                  value: task.statistics.high_risk_count ?? 0,
                  colorType: "high-risk" as const,
                },
                {
                  label: "中危",
                  value: task.statistics.medium_risk_count ?? 0,
                  colorType: "medium-risk" as const,
                },
                {
                  label: "低危",
                  value: task.statistics.low_risk_count ?? 0,
                  colorType: "low-risk" as const,
                },
                {
                  label: "工单数量",
                  value: task.statistics.ticket_count ?? 0,
                },
              ],
            },
          },
        ]
      : []),
    {
      title: "任务基本信息",
      items: [
        {
          key: "task_id",
          label: "任务ID",
          value: task.task_code || task.id || "-",
        },
        {
          key: "task_name",
          label: "任务名称",
          value: task.task_name || "-",
        },
        {
          key: "task_type",
          label: "任务类型",
          value: "手动",
          type: "tag",
          tagType: "info",
        },
        {
          key: "scan_time",
          label: "扫描时间",
          value: task.created_at || task.scan_time || "-",
        },
        {
          key: "scan_duration",
          label: "扫描耗时",
          value: task.scan_duration ? `${task.scan_duration} 秒` : "-",
        },
        {
          key: "creator",
          label: "创建者",
          value: task.created_by || task.creator || "-",
        },
        {
          key: "description",
          label: "备注",
          value: task.description || "无",
          span: 2,
        },
      ],
    },
    {
      title: "资产统计",
      column: 2,
      items: [
        {
          key: "consistent_assets",
          label: "一致资产",
          value: task.consistent_assets
            ? `${task.consistent_assets} (${
                task.consistent_assets_percent || 0
              }%)`
            : "0 (0%)",
          type: "tag",
          tagType: "success",
        },
        {
          key: "unreported_assets",
          label: "未报备资产",
          value: task.unreported_assets
            ? `${task.unreported_assets} (${
                task.unreported_assets_percent || 0
              }%)`
            : "0 (0%)",
          type: "tag",
          tagType: "warning",
        },
        {
          key: "suspected_assets",
          label: "疑似资产",
          value: task.suspected_assets
            ? `${task.suspected_assets} (${
                task.suspected_assets_percent || 100
              }%)`
            : "0 (0%)",
          type: "tag",
          tagType: "danger",
        },
        {
          key: "total_assets",
          label: "总资产数",
          value: task.total_assets || task.asset_count || "0",
          type: "tag",
          tagType: "info",
        },
      ],
    },
    {
      title: "推理进度",
      column: 2,
      items: [
        {
          key: "pending_inference",
          label: "待推理",
          value: String(task.pending_inference || task.pending_count || 0),
        },
        {
          key: "inferred",
          label: "已推理",
          value: String(task.inferred || task.inferred_count || 0),
        },
        {
          key: "confirmed",
          label: "已确认",
          value: String(task.confirmed || task.confirmed_count || 0),
        },
        {
          key: "rejected",
          label: "已拒绝",
          value: String(task.rejected || task.rejected_count || 0),
        },
        {
          key: "inference_progress",
          label: "推理进度",
          value: inferenceProgress,
          span: 2,
          type: "custom",
          slot: "inference_progress",
        },
      ],
    },
    {
      title: "任务配置",
      column: 2,
      items: [
        {
          key: "main_keyword",
          label: "主关键词",
          value: task.main_keyword || "-",
        },
        {
          key: "scenario_types",
          label: "场景类型",
          value: formatScenarioTypes(task.scenario_types),
        },
        {
          key: "schedule_enabled",
          label: "调度状态",
          value: task.schedule_enabled ? "已启用" : "未启用",
          type: "tag",
          tagType: task.schedule_enabled ? "success" : "info",
        },
        {
          key: "cron_expression",
          label: "执行频率",
          value: formatCronExpression(task.cron_expression),
        },
        {
          key: "task_status",
          label: "任务状态",
          value: getStatusText(task.task_status),
          type: "tag",
          tagType: getStatusTagType(task.task_status),
        },
        {
          key: "last_run_time",
          label: "上次执行",
          value: task.last_run_time || "-",
        },
        {
          key: "last_run_status",
          label: "上次执行状态",
          value: getRunStatusText(task.last_run_status),
          type: "tag",
          tagType: getRunStatusTagType(task.last_run_status),
        },
      ],
    },
  ];
});

// 关闭
const handleClose = () => {
  visible.value = false;
};

// 导出报告
const handleExport = () => {
  if (props.taskId) {
    emit("export", props.taskId);
  } else {
    ElMessage.warning("无法导出，任务ID不存在");
  }
};
</script>

<style scoped lang="scss">
// 如果需要自定义样式，可以在这里添加
</style>
